package fr.ece.ing4.si.MonteCarloSeq;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import fr.ece.ing4.si.MonteCarloGUI.myGUI;
import fr.ece.ing4.si.MonteCarloSet.Set;

public class MonteCarloSeq {
	
	//this function calculate the final value
	public Double MonteCarloStandardOption(String CallPutFlag, Double S, Double X, Double T, Double r, Double b, Double v, Integer nSteps, Integer nSimulations) {
		Double dt, St;
		Double Sum, Drift, vSqrdt;
		Integer i, j, z;
		Random rand = new Random();
		Double returnValue;
		
		dt = T/nSteps;
		Drift = (b-(v*v)/2)*dt;
		vSqrdt = v*(Math.sqrt(dt));
		Sum = 0.0;
		z = 0;
		
		if(CallPutFlag.compareTo("c") == 0) {
			z = 1;
		}
		else if (CallPutFlag.compareTo("p") == 0) {
			z = -1;
		}
		
		for(i=0; i<nSimulations;i++) {
			St = S;
			for(j=0;j<nSteps;j++) {
				St = St*Math.exp(Drift+vSqrdt*rand.nextGaussian());
			}
			Sum = Sum + Math.max(z*(St-X), 0);
		}
		
		returnValue = Math.exp(-r * T) * (Sum/nSimulations);
		
		return returnValue;
	}
	
	//this function retrieve all the sets in the txt file
	public static ArrayList<Set> readSets() throws IOException {
	    Set newSet;
		final BufferedReader reader = 
	      new BufferedReader(new FileReader("MonteCarlo_values.txt"));
	    
		//list of sets
	    final ArrayList<Set> Sets = new ArrayList<Set>();
	    
	    String set = null;
	    //retrieve and stock in a new set all the lines in the file
	    while((set = reader.readLine()) != null) {
	    	//cut the line to differenciate the arguments
		      final String[] stockSet = set.split(",");
		      newSet = new Set(Double.valueOf(stockSet[0]), 
		    		  			Double.valueOf(stockSet[1]), 
		    		  			Double.valueOf(stockSet[2]), 
		    		  			Double.valueOf(stockSet[3]), 
		    		  			Double.valueOf(stockSet[4]), 
		    		  			Double.valueOf(stockSet[5]), 
		    		  			Integer.valueOf(stockSet[6]), 
		    		  			Integer.valueOf(stockSet[7]));      
		      Sets.add(newSet); 
	    }

		return Sets;
	}
	
	//this function is the main
	public static void main(final String[] args) 
	throws ExecutionException, IOException, InterruptedException {
		
		//retrieve the sets
		ArrayList<Set> Sets = readSets();
		
		//launch the GUI 
		myGUI GUI = new myGUI(Sets);
		GUI.setVisible(true);
	}
}
